package pro.cherish.knowledgemqrabbitmq.lazy;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-12-03 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：MQSender
 * @Description 功能说明：生产者
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-12-03 cherish
 */

/**
 * 如果消息没有到exchange,则confirm回调,ack=false
 *
 * 如果消息到达exchange,则confirm回调,ack=true
 *
 * exchange到queue成功,则不回调return
 *
 * exchange到queue失败,则回调return(需设置mandatory=true,否则不回回调,消息就丢了)
 */

import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pro.cherish.knowledgemqrabbitmq.t2.RabbitConfig;

import java.util.Date;

@Component
public class MQSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 生产者到交换机，成功则ack为true，回调confirmCallback，否则不回调
     */
    final RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
        System.out.println("correlationData: " + correlationData);
        System.out.println("ack: " + ack);
        if (!ack) {
            System.out.println("异常处理....");
        }
    };
    /**
     * 交换机到队列成功，回调returnCallback，否则不回调
     */
    final RabbitTemplate.ReturnCallback returnCallback = (message, replyCode, replyText, exchange, routingKey) -> System.out.println("return exchange: " + exchange + ", routingKey: "
            + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);

    /**
     * 发送消息
     *
     * @param message
     */
    public void sendLazy(Object message) {
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        //id + 时间戳 全局唯一
        CorrelationData correlationData = new CorrelationData("12345678909" + new Date());
        //发送消息时指定 header 延迟时间
        rabbitTemplate.convertAndSend(RabbitConfig.LAZY_EXCHANGE, "lazy.boot", message,
                message1 -> {
                    //设置消息持久化
                    message1.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    //message.getMessageProperties().setHeader("x-delay", "6000");
                    message1.getMessageProperties().setDelay(6000);
                    return message1;
                }, correlationData);
    }
}
